// Package middleware pkg/middleware/request_memory_monitor.go
package middleware

import (
	"runtime"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gozrd-admin-api/pkg/logger"
)

// RequestMemoryMonitor 监控每个请求的内存消耗
func RequestMemoryMonitor() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 请求前收集内存统计
		var before runtime.MemStats
		runtime.ReadMemStats(&before)

		// 处理请求
		c.Next()

		// 请求后收集内存统计
		var after runtime.MemStats
		runtime.ReadMemStats(&after)

		// 计算内存差异 (KB)
		allocDiff := (after.TotalAlloc - before.TotalAlloc) / 1024
		heapDiff := (after.HeapAlloc - before.HeapAlloc) / 1024

		// 记录内存消耗
		logger.Info("请求内存消耗",
			zap.String("路径", c.Request.URL.Path),
			zap.String("方法", c.Request.Method),
			zap.Int("状态码", c.Writer.Status()),
			zap.Uint64("分配内存(KB)", allocDiff),
			zap.Uint64("堆内存(KB)", heapDiff),
		)
	}
}
